import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_constraintlayout/flutter_constraintlayout.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:wch/constant/resource_constant.dart';
import 'package:wch/helper/preferences_helper.dart';
import 'package:wch/model/flag_model.dart';
import 'package:wch/model/patient_template.dart';
import 'package:wch/native/net_business.dart';
import 'package:wch/utils/digital_utils.dart';
import 'package:wch/utils/log_utils.dart';
import 'package:wch/utils/navigator_utils.dart';
import 'package:wch/utils/time_utils.dart';
import 'package:wch/utils/toast_utils.dart';
import 'package:wch/widget/alert_view.dart';
import 'package:wch/widget/common_widget.dart';
import 'package:wch/widget/padding_widget.dart';
import 'package:wch/widget/text_widget.dart';

import '../constant/event_bus_global.dart';
import '../model/patient_detail.dart';

class NewUserPage extends StatefulWidget {
  const NewUserPage({super.key});

  @override
  State<NewUserPage> createState() => _NewUserPageState();
}

class _NewUserPageState extends State<NewUserPage>
    with WidgetsBindingObserver {
  //处理弹窗的 OverlayEntry
  OverlayEntry? entry;
  List<FlagModel> flagModels = [];
  PatientTemplateModel? templateEntity;
  int selectedId = -1;
  double widgetHeight = 0;

  ///选择的目标下标
  List<Widget> widgets = [];

  List<PatientDetailList> generalList = [];

  ///是否弹出键盘
  bool isPopKeyBoard = false;

  ///页码
  int page = 0;
  ///保存按钮是否高亮
  bool isHighlight = false;

  List<FocusNode> focusNodes = [];

  @override
  void dispose() {
    super.dispose();
    WidgetsBinding.instance.removeObserver(this);
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);

    NetBusiness().patientTemplateList().then((value) {
      templateEntity = value;
      PatientTemplateData data = value.data!;
      flagModels.clear();
      for (int i = 0; i < data.data!.length; i++) {
        String templateName = data.data![i].templateName!;
        if (i == 0) {
          flagModels.add(FlagModel(templateName, true));
        } else {
          flagModels.add(FlagModel(templateName, false));
        }
      }

      if (flagModels.isNotEmpty) {
        _getPatientTemplateDetail(0);
        selectedId = 0;
      }
    });
  }

  @override
  void didChangeMetrics() {
    super.didChangeMetrics();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (mounted) {
        if (MediaQuery.of(context).viewInsets.bottom == 0) {
          // 关闭键盘
          if (!isPopKeyBoard) {
            return;
          }
          setState(() {
            isPopKeyBoard = false;
          //   LogUtils.log('isPopKeyBoard=1');
            isHighlightBtn();
          });
          // _refresh();
        } else {
          // 显示键盘
          if (isPopKeyBoard) {
            return;
          }
          setState(() {
          //   LogUtils.log('isPopKeyBoard=2');
            isPopKeyBoard = true;
          });
          // _refresh();
        }
      }
    });
  }

  void isHighlightBtn() {
    isHighlight = true;
    for(int i = 0; i < generalList.length; i ++) {
      PatientDetailList patientDetailList = generalList[i];
      if (patientDetailList.status == 'Y') {
        if (patientDetailList.controller != null) {
          if (patientDetailList.controller!.text.isEmpty) {
            isHighlight = false;
            break;
          }
        } else {
          if (patientDetailList.text == null || patientDetailList.text!.isEmpty) {
            isHighlight = false;
            break;
          }
        }
      }
    }

  }

  // void test() {
  //   List<PatientDetailList> list = [];
  //   PatientDetailList p1 = PatientDetailList();
  //   p1.type = 0;
  //   p1.name = '年龄';
  //   list.add(p1);
  //
  //   PatientDetailList p2 = PatientDetailList();
  //   p2.type = 1;
  //   p2.name = '姓名';
  //   list.add(p2);
  //
  //   PatientDetailList p3 = PatientDetailList();
  //   p3.type = 2;
  //   p3.name = '生日';
  //   list.add(p3);
  //
  //   PatientDetailList p4 = PatientDetailList();
  //   p4.type = 3;
  //   p4.name = '备注';
  //   list.add(p4);
  //
  //   PatientDetailList p5 = PatientDetailList();
  //   p5.type = 5;
  //   p5.name = '性别';
  //   list.add(p5);
  //
  //   PatientDetailList p6 = PatientDetailList();
  //   p6.type = 3;
  //   p6.name = '备注';
  //   list.add(p6);
  //
  //   PatientDetailList p7 = PatientDetailList();
  //   p7.type = 3;
  //   p7.name = '备注';
  //   list.add(p7);
  //
  //   PatientDetailList p8 = PatientDetailList();
  //   p8.type = 3;
  //   p8.name = '备注';
  //   list.add(p8);
  //
  //   PatientDetailList p9 = PatientDetailList();
  //   p9.type = 3;
  //   p9.name = '备注';
  //   list.add(p9);
  //
  //   widgets.clear();
  //   for (int i = 0; i < list.length; i++) {
  //     PatientDetailList model = list[i];
  //     if (model.type! == 0 || model.type! == 1) {
  //       TextEditingController controller = TextEditingController();
  //       model.controller = controller;
  //       widgets.add(_getInputWidget(controller,
  //           model.name!, model.text, '', model.type!, i != list.length - 1));
  //       widgetHeight += 52.h;
  //     } else if (model.type! == 3){
  //       TextEditingController controller = TextEditingController();
  //       model.controller = controller;
  //       widgets.add(_getMulLineWidget(controller,
  //           model.name!, model.text, '', model.type!, i != list.length - 1));
  //       widgetHeight += 104.h;
  //     } else{
  //       widgets.add(_getSelectWidget(
  //           model.name!, model.text, '', model.type!, i != list.length - 1));
  //       widgetHeight += 52.h;
  //     }
  //   }
  //
  //   setState(() {
  //     widgets;
  //   });
  // }

  void _getPatientTemplateDetail(int index) {
    String id = templateEntity!.data!.data![index].id!;
    NetBusiness().patientTemplateDetail(id).then((value) {
      List<PatientDetailList> list = value.list!;

      if (list.isEmpty) {
        generalList.clear();
        return;
      }

      generalList = list;
      widgetHeight = 0;
      _refresh();
    });
  }

  void _refresh() {
    List<PatientDetailList> list = generalList;
    widgets.clear();
    focusNodes.clear();
    for (int i = 0; i < list.length; i++) {
      PatientDetailList model = list[i];
      TextEditingController controller = TextEditingController();
      model.controller = controller;
      if (model.type! == 0 || model.type! == 1) {
        if (model.name == '科室') {
          widgets.add(_getDepartmentWidget(controller, model.name!, model.type!, i != list.length - 1, model.status == 'Y'));
        } else {
          FocusNode node = FocusNode();
          focusNodes.add(node);
          widgets.add(_getInputWidget(controller, model.name!, model.text,
              '请输入${model.name}', model.type!, i != list.length - 1, model.status == 'Y', node));
        }
        widgetHeight += 52.h;
      } else if (model.type! == 3) {
        FocusNode node = FocusNode();
        focusNodes.add(node);
        widgets.add(_getMulLineWidget(controller, model.name!, model.text,
            '请选择${model.name}', model.type!, i != list.length - 1, model.status == 'Y', node));
        widgetHeight += 104.h;
      } else {
        model.controller = null;
        widgets.add(_getSelectWidget(i, model, i != list.length - 1));
        widgetHeight += 52.h;
      }
    }

    setState(() {
      widgets;
    });
  }

  void _refreshId(int id) {
    PatientDetailList model = generalList[id];
    if (model.type! == 0 || model.type! == 1) {
      if (model.name == '科室') {
        widgets.add(_getDepartmentWidget(model.controller!, model.name!,  model.type!, id != generalList.length - 1, model.status == 'Y'));
      } else {
        FocusNode node = FocusNode();
        focusNodes.add(node);
        widgets[id] = _getInputWidget(model.controller!, model.name!, model.text,
            '请输入${model.name}', model.type!, id != generalList.length - 1, model.status == 'Y', node);
      }
    } else if (model.type! == 3) {
      widgets[id] = _getSelectWidget(id, model, id != generalList.length - 1);
    } else {
      widgets[id] = _getSelectWidget(id, model, id != generalList.length - 1);
    }
    setState(() {
      widgets;
      isHighlightBtn();
    });
  }

  @override
  Widget build(BuildContext context) {
    return KeyboardDismissOnTap(
      child: CommonScaffold(
          title: '新增用户',
          rightBtn: GestureDetector(
            onTap: () {
              if (flagModels.isEmpty) {
                ToastUtils.showToast(msg: '用户模板正在加载中');
                return;
              }
              entry = OverlayEntry(builder: (ctx) {
                return UserTemplateAlert(
                  title: '选择用户模板',
                  entry: entry!,
                  flagModels: flagModels,
                  callback: (id) {
                    if (id == -1) {
                      return;
                    }
                    // ToastUtils.showToast(msg: '正在载入选择的用户模板');
                    selectedId = id;
                    _getPatientTemplateDetail(id);
                  },
                  selectedId: selectedId,
                );
              });
              Overlay.of(context).insert(entry!);

              // test();
            },
            child: Row(
              children: [
                F14TitleText('用户模板', color: themeColor),
                HorPadding(15.w)
              ],
            ),
          ),
          body: CommonContainer(
              verPadding: 0,
              backgroundColor: Color(0xFFF8F9FB),
              child: ConstraintLayout(
                children: [
                  SingleChildScrollView(
                    child: Column(
                      children: [
                        Container(
                          color: Colors.transparent,
                          height: 15,
                        ),
                        Container(
                            decoration: BoxDecoration(
                              borderRadius:
                                  BorderRadius.all(Radius.circular(7.5.w)),
                              color: Colors.white,
                            ),
                            height: widgetHeight,
                            child: Column(
                              children: widgets,
                            )),
                      ],
                    ),
                  ).applyConstraint(
                      left: parent.left,
                      right: parent.right,
                      top: parent.top,
                      // bottom: parent.top.margin(-595.h),
                      bottom: parent.bottom.margin(isPopKeyBoard ? 0 : 100.h),
                      height: matchConstraint),
                  SizedBox(
                    child: Container(
                      alignment: Alignment.center,
                      width: ScreenUtil().screenWidth,
                      height: 40.h,
                      child: CommonBtn(title: '保存', callback: (){
                        _savedLogic();
                      }, isEnable:isHighlight),)
                  ).applyConstraint(
                    left: parent.left,
                    right: parent.right,
                    bottom: parent.bottom,
                    height: isPopKeyBoard ? 0 : 100.h,
                  )
                ],
              ))),
    );
  }

  void _savedLogic() {
    if (generalList.isEmpty) {
      return;
    }

    String templateId = templateEntity!.data!.data![selectedId].id!;
    List<Map<String, dynamic>> list = [];
    for (int i = 0; i < generalList.length; i++) {
      PatientDetailList model = generalList[i];

      if (model.type == 0 || model.type == 1 || model.type == 3) {

        if (model.status == 'Y' && (model.controller!.text == null || model.controller!.text.isEmpty)) {
          ToastUtils.showToast(msg: '请输入${model.name}');
          return;
        }
        if (model.name!.contains('手机') ) {
          if (!DigitalUtils.chinaPhoneNumber(model.controller!.text)) {
            ToastUtils.showToast(msg: '请输入正确的手机号');
            return;
          }
        }
        Map<String, dynamic> map = {};
        map['templateItemId'] = model.id.toString();
        map['text'] = model.controller!.text ?? '';
        list.add(map);
      } else {
        // LogUtils.log('model.controller!.text=${model.controller!.text}');
        if (model.status == 'Y' && (model.text == null || model.text!.isEmpty)) {
          ToastUtils.showToast(msg: '请选择${model.name}');
          return;
        }
        Map<String, dynamic> map = {};
        map['templateItemId'] = model.id.toString();
        map['text'] = model.text ?? '';
        list.add(map);
      }
    }

    NetBusiness().addPatient(templateId, list).then((value) {
      if (value) {
        ToastUtils.showToast(msg: '添加成功');
        Timer.periodic(const Duration(seconds: 1), (timer) {
          timer.cancel();
          globalEventBus.fire(EventBufRefreshModel());
          NavigatorUtil.pop(context);
        });
      }
    });
  }

  Widget _getInputWidget(TextEditingController controller, String label,
      String? content, String? hint, int inputType, bool isNeedLine, bool isRequire, FocusNode focusNode) {
    return Container(
      height: 52.h,
      child: Column(
        children: [
          Expanded(
            child: Row(
              children: [
                HorPadding(20.w),
                Container(
                  width: 120.w,
                  child: F15TitleText(isRequire ? '*$label' : label, color: F1TextColor),
                ),
                Expanded(
                    child: CupertinoTextField(
                  placeholderStyle: TextStyle(
                    color: hintColor,
                    fontSize: 15.w,
                  ),
                  maxLength: label == '手机号' ? 11 : 100,
                  placeholder: hint,
                  controller: controller,
                  focusNode: focusNode,
                  style: TextStyle(color: F1TextColor, fontSize: 15.w),
                  decoration: const BoxDecoration(color: Colors.transparent),
                  keyboardType: inputType == 0
                      ? TextInputType.number
                      : TextInputType.text,
                )),
                HorPadding(20.w)
              ],
            ),
          ),
          Offstage(
            offstage: !isNeedLine,
            child:
                LineWidget(width: ScreenUtil().screenWidth - 30.w, height: 0.5),
          )
        ],
      ),
    );
  }

  ///科室控件
  Widget _getDepartmentWidget(TextEditingController controller, String label, int inputType, bool isNeedLine, bool isRequire) {
    String department =  PreferencesHelper.getDepartment()!;
    controller.text = department;
    return Container(
      height: 52.h,
      child: Column(
        children: [
          Expanded(
            child: Row(
              children: [
                HorPadding(20.w),
                Container(
                  width: 120.w,
                  child: F15TitleText(isRequire ? '*$label' : label, color: F1TextColor),
                ),
                Expanded(
                    child: Row(
                      children: [
                        HorPadding(5.5.w),
                        F15TitleText(department, color: F1TextColor),
                      ],
                    )),
                HorPadding(20.w)
              ],
            ),
          ),
          Offstage(
            offstage: !isNeedLine,
            child:
                LineWidget(width: ScreenUtil().screenWidth - 30.w, height: 0.5),
          )
        ],
      ),
    );
  }

  Widget _getMulLineWidget(TextEditingController controller, String label,
      String? content, String? hint, int inputType, bool isNeedLine, bool isRequire, FocusNode focusNode) {
    return Container(
      height: 104.h,
      child: Column(
        children: [
          Expanded(
            child: Row(
              children: [
                HorPadding(20.w),
                Container(
                  width: 120.w,
                  child: F15TitleText(isRequire ? '*$label' : label, color: F1TextColor),
                ),
                Expanded(
                    child: Container(
                  height: 84.h,
                  padding: EdgeInsets.symmetric(vertical: 10.h),
                  child: CupertinoTextField(
                    placeholderStyle: TextStyle(
                      color: hintColor,
                      fontSize: 15.w,
                    ),
                    maxLines: 10,
                    maxLength: 50,
                    controller: controller,
                    focusNode: focusNode,
                    // style: TextStyle(color: F1TextColor, fontSize: 15.w),
                    // decoration: BoxDecoration(color: Colors.transparent),
                    keyboardType: inputType == 0
                        ? TextInputType.number
                        : TextInputType.text,
                  ),
                )),
                HorPadding(20.w)
              ],
            ),
          ),
          Offstage(
            offstage: !isNeedLine,
            child:
                LineWidget(width: ScreenUtil().screenWidth - 30.w, height: 0.5),
          )
        ],
      ),
    );
  }

  Widget _getSelectWidget(int id, PatientDetailList data, bool isNeedLine) {
    if (isPopKeyBoard) {
      LogUtils.log('_getSelectWidget');
      return _getSelectSubWidget(data, isNeedLine);
    }
    return InkWell(
      onTap: () {
        // focusNode.unfocus();
        for (int i = 0; i < focusNodes.length; i ++) {
          focusNodes[i].unfocus();
        }
        if (data.type == 2) {
          entry = OverlayEntry(builder: (ctx) {
            return SelectDatePicker(
                callback: (date, age) {
                  data.text = date;
                  _refreshId(id);
                },
                overlay: entry!,
                date: TimeUtils.getCurDate('-'),
                title: '请选择日期');
          });
          Overlay.of(context).insert(entry!);
        } else if (data.type == 4 || data.type == 5 || data.type == 6) {
          if (data.name == '性别') {
            data.label = '男,女';
          }
          if (data.label == null) {
            ToastUtils.showToast(msg: 'label 字段为空');
            return;
          }
          entry = OverlayEntry(builder: (ctx) {
            // return SelectSexPicker(callback: (sex){
            //   data.text = sex;
            //   _refreshId(id);
            // }, overlay: entry!);
            return SelectSinglePicker(
              callback: (item) {
                data.text = item;
                _refreshId(id);
              },
              overlay: entry!,
              items: data.label!.split(','),
              title: data.status == 'Y' ? '请选择${data.name}' : '请选择${data.name}',
            );
          });
          Overlay.of(context).insert(entry!);
        }
      },
      child: _getSelectSubWidget(data, isNeedLine)
    );
  }

  Widget _getSelectSubWidget(PatientDetailList data, bool isNeedLine) {
    return Container(
      height: 52.h,
      child: Column(
        children: [
          Expanded(
            child: Row(
              children: [
                HorPadding(20.w),
                Container(
                  width: 127.w,
                  child: F15TitleText(data.status == 'Y' ? '*${data.name!}' : data.name!, color: F1TextColor),
                ),
                Expanded(
                    child: F15TitleText(
                      data.text ?? '请选择${data.name}',
                      color: data.text != null ? F1TextColor : hintColor,
                    )
                  // child: CupertinoTextField(
                  //   placeholderStyle: TextStyle(
                  //     color: hintColor,
                  //     fontSize: 15.w,
                  //   ),
                  //   placeholder: '请选择${data.name}',
                  //   enabled: false,
                  //   controller: data.controller,
                  //   style: TextStyle(color: F1TextColor, fontSize: 15.w),
                  //   decoration: const BoxDecoration(color: Colors.red),
                  //   keyboardType: data.type == 0 ? TextInputType.number : TextInputType.text,
                  // ),
                ),
                HorPadding(10.w),
                Image.asset(
                  arrowRightPng,
                  width: 11.w,
                  height: 11.w,
                ),
                HorPadding(20.w)
              ],
            ),
          ),
          Offstage(
            offstage: !isNeedLine,
            child: LineWidget(
                width: ScreenUtil().screenWidth - 30.w, height: 0.5),
          )
        ],
      ),
    );
  }
}
